<?php

namespace Vanthink\Wordbank\Helper;

use QL\QueryList;

class PhoneticCollectionHelper
{
    private $phonetic_url;

    /**
     * 构造函数
     * @author weiyuzhu
    **/
    public function __construct($phonetic_url = [])
    {
        $this->phonetic_url = $phonetic_url;
    }

    /**
     * 单词音标采集
     * @author weiyuzhu
     * @param array $words ['along']
     * @return ['along' => 'əˈlɒŋ']
    **/
    public function getCollectionPhonetic(array $words)
    {
        try {
            $return = [
                'code' => 200,
                'data' => []
            ];
            foreach ($words as $word) {
                //朗文采集
                $url = $this->phonetic_url['l'].$word;
                $phonetic = $this->getFromContent($url, 'l');
                if (!$phonetic) {
                    //有道翻译
                    $url = $this->phonetic_url['y'].$word;
                    $phonetic = $this->getFromContent($url, 'y');
                }
                if ($phonetic) {
                    $return['data'][$word] = $phonetic;
                }
            }
        } catch (\Exception | \Error $e) {
            return ['code' => 100, 'data' => $e];
        }
        return $return;
    }

    /**
     * 采集
     * @author weiyuzhu
    **/
    private function getFromContent($url, $type)
    {
        $phonetic = '';
        $opts = ['https' => ['method' => "GET", 'timeout' => 60]];
        $context = stream_context_create($opts);
        $html  = file_get_contents($url,  false, $context);
        $i=0;
        while(!$html && $i < 4){
            $html = file_get_contents($url,  false, $context);
            $i++;
        }
        if($i == 4) {
            return $phonetic;
        };
        $rt = [];
        $ql = QueryList::html($html);
        switch ($type) {
            case 'l':
                $rt[] = $ql->find('.PronCodes>span:eq(1)')->text();
                break;
            case 'y':
                $rt[] = $ql->find('.phonetic:eq(0)')->text();
        }
        $phonetic = isset($rt[0]) && $rt[0] ? $rt[0] : null;
        if ($phonetic) $phonetic = $this->strReplace($phonetic);
        return $phonetic;
    }

    /**
     * 特殊符号剔除
     * @author weiyuzhu
    **/
    private function strReplace($phonetic)
    {
        //特殊符号
        $arr = ['◂', '[', ']'];
        foreach ($arr as $value)
        {
            $phonetic = str_replace($value, "", $phonetic);
        }
        return trim($phonetic);
    }
}